import bs4
import requests
from urllib.parse import urljoin

FILE_ENCODING = 'utf-8'


def diff():
    f_iptv = open('iptv.m3u', mode='r', encoding=FILE_ENCODING)

    f_empty = open('empty.m3u', mode='r', encoding=FILE_ENCODING)

    iptv_list = set(filter(lambda line: line.startswith('#'), f_iptv.readlines()))

    empty_list = set(f_empty.readlines())

    print('多了：')
    for i in iptv_list.difference(empty_list):
        print(i)

    print('少了：')
    for i in empty_list.difference(iptv_list):
        print(i)


def update_empty_m3u_file_from(site):
    f_target = open('empty.m3u', mode='w', encoding=FILE_ENCODING)

    f_target.write('#EXTM3U\n\n')

    def get_tags(element):
        return list(filter(lambda e: isinstance(e, bs4.Tag), element))

    resp = requests.get(site, headers={
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
    })

    resp.encoding = 'utf-8'

    html = bs4.BeautifulSoup(resp.text, features='html.parser')

    for tr in get_tags(html.body.div.table.tbody.children):

        _, td_logo, td_name, td_tv_name, td_tv_id, td_group, _, _ = get_tags(tr.children)

        logo_short = td_logo.a['href'].lstrip('.')

        if logo_short in ['#']:
            continue

        logo_url = urljoin(site, logo_short)

        f_target.write(
            f'#EXTINF:-1 tvg-id="{td_tv_id.text}" tvg-name="{td_tv_name.text}" tvg-logo="{logo_url}"'
            f' group-title="{td_group.text}",{td_name.text}\n\n')

    f_target.close()


if __name__ == '__main__':
    diff()
